//
//  TakePacket.m
//  Proto
//
//  Created by kingly on 15/11/23.
//  Copyright © 2015年 Will. All rights reserved.
//

#import "TakePacket.h"

@interface TakePacket (){
    
    
    NSUInteger protoDataLength;     //protoData的长度
    NSMutableData* cachServiceData;  //缓成服务器放回的数据
    
}
@end

@implementation TakePacket

-(id)init
{
    if(self = [super init])
    {
        cachServiceData = [NSMutableData data];
    }
    return self;
}


/**
 * 拆分获得的数据包
 */
- (NSData *)takeDataToByteStream{
    if (_receivedData == nil) {
        return nil;
    }
    [cachServiceData appendData:_receivedData];
    NSLog(@"cachServiceData length=%lu",(unsigned long)cachServiceData.length);
    protoDataLength = [self getLengthOfData:[cachServiceData subdataWithRange:NSMakeRange(0, 4)]];
    
    if (protoDataLength>0) {
        
        NSData *proData = [cachServiceData subdataWithRange:NSMakeRange(4, protoDataLength)];
        //接收数据完成清除cachServiceData
        cachServiceData = [NSMutableData dataWithData:[cachServiceData subdataWithRange:NSMakeRange(protoDataLength+4,0)]];
        return proData;
        
    }

    return nil;
}

/**
 * 接收服务器的的数据 从低位到高位 读取
 */
- (NSUInteger) getLengthOfData:(NSData*)data
{
    Byte *dataPointer = (Byte *)[data bytes];
    NSUInteger result = 0;
    for (NSUInteger index = 0; index < 4; index++)
    {
        result += dataPointer[index]<<(8*index);
    }
    return result;
}


@end
